//
//  HomeViewController.swift
//  MT
//
//  Created by ooops on 2019/7/18.
//  Copyright © 2019年 张强. All rights reserved.
//

import UIKit
/// 网络、通用
import MTCategory

import Moya
import Result
import RxSwift
import RxCocoa
/// 其它
import JXPagingView
import JXCategoryView
import MJRefresh
import YPNavigationBarTransition
import CWLateralSlide

class HomeViewController: BaseViewController {
    
    /// Publish Provider
    private lazy var publishProvider: MTProvider<PublishApi> = {
        return MTProvider<PublishApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    /// Oss Provider
    private lazy var ossProvider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    
    /// 列表展示性别 - 默认为不限
    var displayGenderType: LocalGenderModel.GenderType = .unknown

    /// PagingView 子控制器
    var controllers: [HomeListTableViewController] = []
    
    /// 上传模型
    var uploadingModels: [HomeUploadModel] = [] {
        didSet {
            uploadTableView.snp.updateConstraints { (make) in
                make.top.equalTo(view).offset(StatusBarHeight + NavigationBarHeight)
                make.height.equalTo(40.0 * CGFloat(uploadingModels.count))
            }
            self.uploadTableView.models = uploadingModels
        }
    }
    
    /// 分类标题名称
    private var titles: [String] {
        return ["热门", "同城"]
    }
    /// 分类标题视图
    lazy var categoryView: JXCategoryTitleView = {
        let titleView = JXCategoryTitleView(frame: CGRect(x: (ScreenWidth - 210) / 2, y: 5, width: 210, height: NavigationBarHeight - 10))
        titleView.titles = self.titles
        titleView.delegate = self
        /// 字体设置
        titleView.titleFont = PingFangSCSemiboldFont(18)
        titleView.titleSelectedFont = PingFangSCSemiboldFont(18)
        /// 颜色设置
        titleView.titleColor = .white
        titleView.titleSelectedColor = UIColor(hex:0xffc000)
        /// 背景颜色
        titleView.cellWidth = 105
        titleView.indicators = [indicatoryView]
        titleView.selectedAnimationDuration = 0
        titleView.cellSpacing = 0
        titleView.isTitleColorGradientEnabled = true
//        titleView.layer.cornerRadius = 3
//        titleView.clipsToBounds = true
//        titleView.layer.borderWidth = 1
//        titleView.layer.borderColor = UIColor(hex: 0x3e3e3e).cgColor
        return titleView
    }()
    
    private lazy var indicatoryView: JXCategoryIndicatorBackgroundView = {
        let indicatory: JXCategoryIndicatorBackgroundView = JXCategoryIndicatorBackgroundView()
        indicatory.indicatorColor = UIColor(hex:0xffc000)
        indicatory.indicatorHeight = 3
        indicatory.indicatorCornerRadius = 0
        indicatory.indicatorWidth = 20
        indicatory.verticalMargin = -15
        
        return indicatory
    }()
    
    /// 分页视图
    lazy var pagingView: JXPagingView = {
        let p = JXPagingView(delegate: self)
        p.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight - TabBarHeight - NavigationBarHeight - StatusBarHeight)
        p.isListHorizontalScrollEnabled = false
        p.mainTableView.backgroundColor = UIColor(hex:0x000000)
        p.mainTableView.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(refreshHeaderAndReloadData))
            //MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshHeaderAndReloadData))
        return p
    }()
    
    /// 上传列表 TableView
    lazy var uploadTableView: HomeUploadTableView = {
        let tv = HomeUploadTableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 1))
        tv.contentInsetAdjustmentBehavior = .always
        return tv
    }()
    
    lazy var agreementViewBack: UIView = {
        let v = UIView()
        v.frame = view.bounds
        v.backgroundColor = UIColor(hex: 0x000000, alpha: 0.6)
        return v
    }()
    
    lazy var agreementView: MTAgreementView = {
        let v = MTAgreementView()
        v.delegate = self
        v.layer.cornerRadius = 5
        v.backgroundColor = UIColor.theme.main
        return v
    }()
    
    deinit {
        removeNotifications()
    }
    
}

extension HomeViewController: MTAgreementViewDelegate {
    func dismiss(isCancel: Bool) {
        if isCancel == false {
            UserDefaults.AppValidate.isConfirmUserAgreement.store(value: true)
        }
        agreementViewBack.removeFromSuperview()
    }
    
    func userAgreement() {
        agreementViewBack.isHidden = true
        let c = MTMineWebViewController()
        c.selectValue = 0
        c.delegate = self
        self.navigationController?.pushViewController(c, animated: true)
    }
    
    func privacy() {
        agreementViewBack.isHidden = true
        let c = MTMineWebViewController()
        c.selectValue = 1
        c.delegate = self
        self.navigationController?.pushViewController(c, animated: true)
    }
}

extension HomeViewController: MTMineWebViewControllerDelegate {
    func navigation() {
        agreementViewBack.isHidden = false
    }
}

// MARK: ------------------ Overrides ----------------------
extension HomeViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        observeNotifications()
        addEdgeInteractiveControllerPresentGesture()

    }
}

// MARK: ------------------ UI Initialize ----------------------
extension HomeViewController {
    
    private func initializeUI() {
        navigationItem.titleView = categoryView
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
        button.setImage(UIImage(named: "publish"), for: .normal)
        button.addTarget(self, action: #selector(homeViewController(didClickRightBarButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
        btn.setImage(UIImage(named: "condition"), for: .normal)
        btn.addTarget(self, action: #selector(homeViewController(didClickLeftBarButton:)), for: .touchUpInside)
        let leftBarButton = UIBarButtonItem(customView: btn)
        self.navigationItem.leftBarButtonItem = leftBarButton
        
        view.addSubview(pagingView)

        pagingView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }

        view.addSubview(uploadTableView)
        uploadTableView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(StatusBarHeight + NavigationBarHeight)
            make.left.right.equalTo(view)
            make.height.equalTo(0)
        }
        
        if UserDefaults.AppValidate.isConfirmUserAgreement.storedBool == false {
            //view.addSubview(agreementView)
            UIApplication.shared.keyWindow?.addSubview(agreementViewBack)
            agreementViewBack.addSubview(agreementView)
            
            agreementView.snp.makeConstraints { (make) in
                make.center.equalToSuperview()
                make.width.equalTo(ScreenWidth * 0.75)
                make.height.equalTo(ScreenWidth * 0.65 * 1.2)
            }
        }
        
        
        //categoryView.contentScrollView = pagingView.listContainerView.collectionView
    }
    
    private func addEdgeInteractiveControllerPresentGesture() {
        self.cw_registerShowIntractive(withEdgeGesture: true) { [weak self] (direction) in
            guard let weakself = self else { return }
            if direction == .fromRight {
                let controller = weakself.controllers[weakself.categoryView.selectedIndex]
                let cell = controller.tableView.visibleCells.first as? HomeListTableViewCell
                guard let username = cell?.model?.userName else { return }
                let c = MineViewController(username: username) {
                    controller.play()
                }
                c.showBackButton = true
                let nav = BaseNavController(rootViewController: c)
                let conf: CWLateralSlideConfiguration = CWLateralSlideConfiguration.default()
                conf.direction = CWDrawerTransitionDirection.fromRight
                conf.distance = Float(ScreenWidth)
                controller.pause()
                weakself.cw_showDrawerViewController(nav, animationType: .mask, configuration: conf)
            }
        }
    }
    
}

// MARK: ------------------------------------ 通知相关 ----------------------------------------
extension HomeViewController {
    
    /// 添加通知监听
    private func observeNotifications() {
        /// 监听用户信息通知
        NotificationCenter.default.addObserver(self, selector: #selector(userInfoNotification(notification:)), name: GlobalNotificationName.homeInteractionUserInfo.name, object: nil)
        /// 监听加好友通知
        NotificationCenter.default.addObserver(self, selector: #selector(addFriendNotification(notification:)), name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil)
        /// 监听送礼物通知
        NotificationCenter.default.addObserver(self, selector: #selector(sendGiftNotification(notification:)), name: GlobalNotificationName.homeInteractionSendGift.name, object: nil)
        /// 监听发帖
        NotificationCenter.default.addObserver(self, selector: #selector(publish(notification:)), name: GlobalNotificationName.publishPost.name, object: nil)
    }
    
    /// 移除所有通知
    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.homeInteractionUserInfo.name, object: nil)
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil)
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.homeInteractionSendGift.name, object: nil)
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.publishPost.name, object: nil)
    }
    
}

// MARK: ------------------------------------ 事件方法 ----------------------------------------
@objc
extension HomeViewController {
    
    /// 重新刷新数据
    private func refreshHeaderAndReloadData() {
        controllers[categoryView.selectedIndex].reloadAllData { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.pagingView.mainTableView.mj_header?.endRefreshing()
        }
    }
    
    /// 点击右上 navigationBar 按钮
    private func homeViewController(didClickRightBarButton sender: UIButton) {
        let c = PublishViewController()
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    private func homeViewController(didClickLeftBarButton sender: UIButton) {
        self.presentGenderAlertView(selectedType: self.displayGenderType) { [weak self] (type) in
            guard let weakSelf = self else { return }
            if weakSelf.displayGenderType != type {
                weakSelf.displayGenderType = type
                for i in 0..<weakSelf.controllers.count {
                    weakSelf.controllers[i].setGenderType(type, isCurrentPagingController: i == weakSelf.categoryView.selectedIndex)
                }
            }
        }
    }
    
    /// 用户信息通知接收
    private func userInfoNotification(notification: Notification) {
        guard let username = notification.userInfo?["username"] as? String else { return }
        let c = MineViewController(username: username)
        self.navigationController?.pushViewController(c, animated: true)
    }
    
    /// 加好友通知接收
    private func addFriendNotification(notification: Notification) {
        /// 是否添加成功通知
        guard let isSuccess = notification.userInfo?["isSuccess"] as? Bool else { return }
        //AlertManager.presentAlertView(message: isSuccess ? "添加好友成功" : "添加好友失败", duration: 1)
        //AlertManager.presentAlertView(message: isSuccess ? "好友请求已发送,等待对方验证" : "好友请求发送失败", duration: 1)
        
    }
    
    /// 送礼物通知接收
    private func sendGiftNotification(notification: Notification) {
        /// 极光用户名
        guard let username = notification.userInfo?["imUserName"] as? String else { return }
        guard let isFriend = notification.userInfo?["isFriend"] as? Bool else { return }
        
        self.presentGiftView(isFriend: isFriend, imUserName: username, didClickRechargeCallBack: { [weak self] in
            guard let weakself = self else { return }
            if UserDefaults.AppValidate.isValidate.storedBool == false {
                let c = MTPaymentViewController()
                weakself.navigationController?.pushViewController(c, animated: true)
            } else {
                let c = MTInAppPurchasesViewController()
                weakself.navigationController?.pushViewController(c, animated: true)
            }
            }, selectedGiftCallBack: { [weak self] (model, count) in
                guard let weakself = self else { return }
                let c = MTAddFriendViewController(giftCount: count, targetUserName: username, giftModel: model)
                weakself.navigationController?.pushViewController(c, animated: true)
        }, didClickSayHiCallBack: { (model, count) in
            
        }) {
            
        }
    }
    
    /// 发布通知
    private func publish(notification: Notification) {
        guard let assets = notification.userInfo?["assets"] as? [MTAsset],
            let content = notification.userInfo?["content"] as? String else {
            return
        }
        process(assets: assets, content: content, area: notification.userInfo?["area"] as? String)
    }
    
}

// MARK: ------------------------------------ 发布相关 ----------------------------------------
extension HomeViewController {
    
    private func process(assets: [MTAsset], content: String, area: String?) {
        /// 发布文字
        if assets.count == 0 {
            publish(content: content, area: area)
            return
        }
        /// 是否视频发布
        let isVideoPublish: Bool = assets.first?.mediaType == .video
        if isVideoPublish {
            publishVideo(asset: assets[0], content: content, area: area)
        } else {
            publishImages(assets: assets, content: content, area: area)
        }
    }
    
    /// 发布文本
    private func publish(content: String, area: String?) {
        publishProvider.rx.requestResult(.post(area: nil, content: content, imgList: nil)).subscribe(onNext: { (result: Result<MineInfoListModel, AnyError>, isCache: Bool) in
            switch result {
            case let .success(response):
                debugPrint(response)
                break
                
            case .failure(_):
                break
            }
        }).disposed(by: disposeBag)
    }
    
    // MARK: ------------------------------------ 图文发布 ----------------------------------------
    
    /// 发布图文
    private func publishImages(assets: [MTAsset], content: String, area: String?) {
        var images: [UIImage] = [UIImage](repeating: UIImage(), count: assets.count)
        var progressGroup: [Double] = [Double](repeating: 0, count: assets.count)
        let group = DispatchGroup()
        
        /// 创建上传模型
        let m = HomeUploadModel(JSON: ["content": content,
                                       "assets": assets])
        m?.area = area
        m?.msg = "图片处理中..."
        if let m = m {
            uploadTableView.models.append(m)
            uploadTableView.snp.updateConstraints { (make) in
                make.top.equalTo(view)
                make.height.equalTo(40.0 * CGFloat(uploadTableView.models.count))
            }
            uploadTableView.reloadData()
        }
        
        for i in 0..<assets.count {
            group.enter()
            MTAssetLibrary.default.requestImage(withAsset: assets[i].asset) { [weak self] (image, info, isDegraded) in
                guard let weakself = self else { return }
                if isDegraded == false, let image = image {
                    if let m = m {
                        progressGroup[i] = weakself.calculateProgress(group: progressGroup, percentage: 0.01, doneProgress: 0)
                        weakself.uploadTableView.update(model: m)
                    }
                    images[i] = image
                    group.leave()
                }
            }
        }
        group.notify(queue: .main) {
            if let m = m {
                self.upload(images: images, model: m, percentage: 0.01 * Double(images.count))
            }
        }
    }
    
    /// 上传图片
    private func upload(images: [UIImage], model: HomeUploadModel, percentage: Double) {
        var imagePaths: [String] = [String](repeating: "", count: images.count)
        var progressGroup: [Double] = [Double](repeating: 0, count: images.count)
        let group = DispatchGroup()
        
        for i in 0..<images.count {
            group.enter()
            ossProvider.originRequest(.upload(images[i]), callbackQueue: .global(), progress: { [weak self] (progressResponse) in
                guard let weakself = self else { return }
                DispatchQueue.main.async {
                    progressGroup[i] = progressResponse.progress
                    model.progress = weakself.calculateProgress(group: progressGroup, percentage: 1.0 - percentage - 0.01, doneProgress: percentage)
                    weakself.uploadTableView.update(model: model)
                }
            }) { [weak self] (result, _) in
                guard let weakself = self else { return }
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                        if code == 200, let url = datas["result"] as? String {
                            imagePaths[i] = url
                            group.leave()
                        } else {
                            DispatchQueue.main.async {
                                model.status = .fail
                                model.msg = "图片上传失败"
                                weakself.uploadTableView.update(model: model)
                            }
                        }
                    }
                    break
                    
                case .failure(_):
                    break
                }
            }
        }
        
        group.notify(queue: .main) {
            model.imagePaths = imagePaths
            self.publish(model: model)
        }
    }
    
    // MARK: ------------------------------------ 视频发布 ----------------------------------------
    
    /// 缓存视频地址
    var local_video_path: String {
        let s = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as AnyObject
        return s.appending("/verifyVideo.mov")
    }
    /// 发布视频
    private func publishVideo(asset: MTAsset, content: String, area: String?) {
        /// 删除视频
        if FileManager.default.fileExists(atPath: local_video_path) {
            try? FileManager.default.removeItem(atPath: local_video_path)
        }
        
        /// 创建上传模型
        let m = HomeUploadModel(JSON: ["content": content, "assets": [asset]])
        m?.area = area
        m?.msg = "视频处理中..."
        if let m = m {
            uploadTableView.models.append(m)
            uploadTableView.snp.updateConstraints { (make) in
                make.top.equalTo(view)
                make.height.equalTo(40.0 * CGFloat(uploadTableView.models.count))
            }
            uploadTableView.reloadData()
        }
        
        MTAssetLibrary.default.requestVideo(withAsset: asset.asset, progressHandler: { [weak self] (progress) in
            guard let weakself = self else { return }
            m?.progress = weakself.calculateProgress(group: [progress], percentage: 0.1, doneProgress: 0)
        }, errorHandler: { (error) in
            m?.status = .fail
            m?.msg = error?.localizedDescription
        }, assetCompletion: nil) { [weak self] (progress, path) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                m?.progress = weakSelf.calculateProgress(group: [Double(progress)], percentage: 0.15, doneProgress: 0.1)
                if let m = m { weakSelf.uploadTableView.update(model: m) }
            }
            if let path = path, let m = m {
                weakSelf.requestCoverImage(videoPath: path, asset: asset, model: m)
            }
        }
    }
    
    /// 获取封面图
    private func requestCoverImage(videoPath: String, asset: MTAsset, model: HomeUploadModel) {
        MTAssetLibrary.default.requestImage(withAsset: asset.asset, photoWidth: ScreenWidth) { [weak self] (image, info, isDegraded) in
            guard let weakself = self, let image = image else { return }
            if isDegraded == false {
                weakself.upload(videoPath: videoPath, coverImage: image, model: model)
            }
        }
    }
    
    /// 上传视频
    private func upload(videoPath: String, coverImage: UIImage, model: HomeUploadModel) {
        var progressGroup: [Double] = [Double](repeating: 0, count: 2)
        let group = DispatchGroup()
        
        /// 进入 上传封面图 group
        group.enter()
        ossProvider.originRequest(.upload(coverImage), callbackQueue: .global(), progress: { [weak self] (progressResponse) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                progressGroup[0] = progressResponse.progress
                model.progress = weakself.calculateProgress(group: progressGroup, percentage: 0.74, doneProgress: 0.25)
                weakself.uploadTableView.update(model: model)
            }
        }) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200, let url = datas["result"] as? String {
                        model.uploadCoverImagePath = url
                        group.leave()
                    } else {
                        DispatchQueue.main.async {
                            model.status = .fail
                            model.msg = "封面图上传失败"
                            weakself.uploadTableView.update(model: model)
                        }
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }
        
        /// 进入上传视频 group
        group.enter()
        ossProvider.originRequest(.uploadVideo(URL(fileURLWithPath: videoPath)), callbackQueue: .global(), progress: { [weak self] (progressResponse) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                progressGroup[1] = progressResponse.progress
                model.progress = weakself.calculateProgress(group: progressGroup, percentage: 0.74, doneProgress: 0.25)
                weakself.uploadTableView.update(model: model)
            }
        }) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200, let url = datas["result"] as? String {
                        model.uploadVideoPath = url
                        group.leave()
                    } else {
                        DispatchQueue.main.async {
                            model.status = .fail
                            model.msg = "视频上传失败"
                            weakself.uploadTableView.update(model: model)
                        }
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }
        
        group.notify(queue: .main) {
            self.publish(model: model)
        }
    }
    
    // MARK: ------------------------------------ 发布 ----------------------------------------
    
    /// 图文 、视频发布
    private func publish(model: HomeUploadModel) {
        guard let content = model.content else { return }
        var imgList: [UserMediaListModel]?
        if let videoPath = model.uploadVideoPath, let coverImage = model.uploadCoverImagePath {
            if let model = UserMediaListModel(JSON: ["coverImg": coverImage,
                                                     "href": videoPath,
                                                     "objType": 1]) {
                imgList = [model]
            }
        } else if let imagePaths = model.imagePaths {
            imgList = []
            for path in imagePaths {
                if let model = UserMediaListModel(JSON: ["href": path,
                                                         "objType": 0]) {
                    imgList?.append(model)
                }
            }
        }
        
        publishProvider.rx.requestResult(.post(area: model.area, content: content, imgList: imgList)).subscribe(onNext: { [weak self] (result: Result<MineInfoSignleResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    DispatchQueue.main.async {
                        model.progress = 1
                        model.status = .success
                        model.msg = "上传成功"
                        weakself.uploadTableView.update(model: model)
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            weakself.uploadTableView.remove(model: model)
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        model.status = .fail
                        model.msg = "上传失败"
                        weakself.uploadTableView.update(model: model)
                    }
                }
                
                break
                
            case .failure(_):
                DispatchQueue.main.async {
                    model.status = .fail
                    model.msg = "上传失败"
                    weakself.uploadTableView.update(model: model)
                }
                break
            }
        }).disposed(by: disposeBag)
    }
    
    /**
     计算进度
     
     group: 进度数组
     percentage: 此次进度总占比
     doneProgress: 已完成进度
     */
    private func calculateProgress(group: [Double], percentage: Double, doneProgress: Double) -> Double {
        return group.reduce(0, { (r, p) -> Double in
            return r + p
        }) / Double(group.count) * percentage + doneProgress
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ JXCategoryTitleView 代理 ----------------------
extension HomeViewController: JXCategoryViewDelegate {
    
    func categoryView(_ categoryView: JXCategoryBaseView!, scrollingFromLeftIndex leftIndex: Int, toRightIndex rightIndex: Int, ratio: CGFloat) {
        controllers[categoryView.selectedIndex].pause()
        for c in controllers {
            c.currentDisplayingController = controllers[categoryView.selectedIndex]
        }
    }
    
    func categoryView(_ categoryView: JXCategoryBaseView!, didSelectedItemAt index: Int) {
        navigationController?.navigationBar.backgroundColor = index == 0 ? UIColor(hex: 0x000000) : UIColor.black.withAlphaComponent(0.1)
        controllers[0].pause()
        for c in controllers {
            c.currentDisplayingController = controllers[0]
            c.dataDisplayType = (index == 0 ? .hottest : .latest)
        }
    }
    
}

// MARK: ------------------ JXPagingView 代理 ----------------------
extension HomeViewController: JXPagingViewDelegate {
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return 0
    }
    
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return UIView()
    }
    
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return 0
    }
    
    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return UIView()
    }
    
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return self.titles.count
    }

    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        let controller = HomeListTableViewController(dataDisplayType: index == 0 ? .hottest : .latest)
        controllers.append(controller)
        controller.currentDisplayingController = controllers[0]
        return controller
    }
    
}

extension HomeViewController {

    override func yp_navigationBarTintColor() -> UIColor! {
        return UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack]
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        return UIColor(hex: 0x000000)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

